package com.rajaev.dtu.tractor.app.listener;

import com.alibaba.fastjson.JSONObject;
import com.gizwits.noti.noticlient.OhMyNotiClient;
import com.gizwits.noti.noticlient.OhMyNotiClientImpl;
import com.rajaev.dtu.tractor.app.service.SNotiMessageProcessor;
import com.rajaev.dtu.tractor.domain.entity.SnotiMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SnotiListener implements ApplicationListener<ApplicationReadyEvent> {


    @Autowired
    OhMyNotiClient ohMyNotiClient;


    private static String threadName = "listen-snoti-message";

    @Autowired
    SNotiMessageProcessor sNotiMessageProcessor;

    void listenSnotiMessage() {
        new Thread(() -> {
            ohMyNotiClient.doStart();
            while (true) {
                try{
                    JSONObject snotiMessage = ohMyNotiClient.receiveMessage();
                    SnotiMessage snotiMessageObj = JSONObject.toJavaObject(snotiMessage, SnotiMessage.class);
                    sNotiMessageProcessor.processMessage(snotiMessageObj);
                }catch (Exception e){
                    log.error("数据解析的异常信息",e);
                }

            }
        }, threadName).start();

    }


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        listenSnotiMessage();

    }
}
